<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-21 23:03:53
 * Desc: 微信公众号消息处理service
 */

namespace app\base\service\WeChat;

use app\base\service\BaseService;
use EasyWeChat\Factory;
use app\core\log\Log4dd;
use app\core\exception\BusinessException;

class OfficialAccountMessageHandlerService extends BaseService
{

    protected $ToUserName; // 接收方帐号（该公众号 ID）
    protected $FromUserName; // 发送方帐号（OpenID, 代表用户的唯一标识）
    protected $CreateTime; // 消息创建时间（时间戳）
    protected $MsgId; // 消息 ID（64位整型）
    protected $MsgType;// 消息 类型

    public static function AutoReply($appId = '')
    {
        try {
            $app = Factory::officialAccount(WeChatBaseService::instance()->getConfigByAppId($appId));
            $app->server->push(function ($message) {
                //$this->MsgType = $message['MsgType'];
                //$this->ToUserName = $message['ToUserName'];
                //$this->FromUserName = $message['FromUserName'];
                //$this->CreateTime = $message['CreateTime'];
                //$this->MsgId = $message['MsgId'];
                switch ($message['MsgType']) {
                    case 'text':
                        return self::textMessageHandler($message['Content']);
                        break;
                    case 'image':
                        //return self::imageMessageHandler($message['MediaId'], $message['PicUrl']);
                        break;
                    case 'voice'://开通语音识别后，有第三个字段
                        //return self::voiceMessageHandler($message['MediaId'], $message['Format']);
                        break;
                    case 'video':
                        //return self::videoMessageHandler($message['MediaId'], $message['ThumbMediaId']);
                        break;
                    case 'shortvideo':
                        //return self::shortVideoMessageHandler($message['MediaId'], $message['ThumbMediaId']);
                        break;
                    case 'location':
                        //return self::locationMessageHandler($message['Location_X'], $message['Location_Y'], $message['Scale'], $message['Label']);
                        break;
                    case 'link':
                        //return self::linkMessageHandler($message['Title'], $message['Description'], $message['Url']);
                        break;
                    case 'file':
                        //return self::fileMessageHandler($message['Title'], $message['Description'], $message['FileKey'], $message['FileMd5'], $message['FileTotalLen']);
                        break;
                    case 'event':
                        $messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
                        //return self::eventHandler($message['Event'], $messageKey);
                        break;
                    default:
                        //return self::textMessageHandler();
                        break;
                }
            });
            $response = $app->server->serve();
            return $response->send();
        } catch (BusinessException $e) {
            Log4dd::error('微信公众号消息发送失败:' . $e->getMessage(), func_get_args(), $e);
        }
    }


    /**
     * Desc:
     * Date: 2020/1/22 0:25
     * Author: yiyu
     * @param string $content 文本消息内容
     * @return object
     */
    private static function textMessageHandler($content = '')
    {
        switch ($content) {
            case 1:
                return SendMessage::instance()->sendTextMsg('您发送了数字1');
                break;
            case 2:
                return SendMessage::instance()->sendTextMsg('您发送了数字2');
                break;
            default:
                return SendMessage::instance()->sendTextMsg('您好，欢迎光临');
                break;
        }

    }


    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $mediaId 图片消息媒体id，可以调用多媒体文件下载接口拉取数据
     * @param string $picUrl 图片链接
     * @return object
     */
    private static function imageMessageHandler($mediaId, $picUrl)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的图片消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $mediaId 图片消息媒体id，可以调用多媒体文件下载接口拉取数据
     * @param string $format 语音格式，如 amr，speex 等
     * @return object
     */
    private static function voiceMessageHandler($mediaId, $format)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的语音消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $mediaId 图片消息媒体id，可以调用多媒体文件下载接口拉取数据
     * @param string $thumbMediaId 视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据
     * @return object
     */
    private static function videoMessageHandler($mediaId, $thumbMediaId)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的视频消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $mediaId 图片消息媒体id，可以调用多媒体文件下载接口拉取数据
     * @param string $thumbMediaId 视频消息缩略图的媒体id，可以调用多媒体文件下载接口拉取数据
     * @return object
     */
    private static function shortVideoMessageHandler($mediaId, $thumbMediaId)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的小视频消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:32
     * Author: yiyu
     * @param string $location_X 地理位置纬度
     * @param string $location_Y 地理位置经度
     * @param string $scale 地图缩放大小
     * @param string $label 地理位置信息
     * @return object
     */
    private static function locationMessageHandler($location_X, $location_Y, $scale, $label)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的地理位置消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:45
     * Author: yiyu
     * @param $title string 消息标题
     * @param $description string 消息描述
     * @param $url string 消息链接
     * @return object
     */
    private static function linkMessageHandler($title, $description, $url)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的链接消息');
    }

    /**
     * Desc:
     * Date: 2020/1/22 0:48
     * Author: yiyu
     * @param $title string 文件名
     * @param $description mixed 文件描述，可能为null
     * @param $fileKey string 文件KEY
     * @param $fileMd5 string 文件MD5值
     * @param $fileTotalLen int  文件大小，单位字节
     * @return object
     */
    private static function fileMessageHandler($title, $description, $fileKey, $fileMd5, $fileTotalLen)
    {
        return SendMessage::instance()->sendTextMsg('我们已经收到了您发送的文件消息');
    }

    /**
     * Desc: 事件处理
     * Date: 2020/1/22 13:13
     * Author: yiyu
     * @param $messageEvent string 事件类型
     * @param $eventKey string 事件key
     * @return mixed
     */
    private static function eventHandler($messageEvent, $eventKey)
    {
        $messageEvent = strtolower($messageEvent);
        switch ($messageEvent) {
            case 'subscribe': // 订阅事件
                return SendMessage::instance()->sendTextMsg('欢迎关注');
                break;
            case 'unsubscribe': // 取消订阅事件
                return null;
                break;
            case 'click': // 处理菜单点击事件
                return self::menuClickEventHandler($eventKey);
                break;
            default:
                return "{$messageEvent}, {$eventKey}";
                break;
        }
    }


    /**
     * Desc: 菜单栏中type为click的按钮才会发送return的消息回去
     * Date: 2020/1/22 13:12
     * Author: yiyu
     * @param $eventKey string 设置菜单时type为click的key值
     * @return object
     */
    private static function menuClickEventHandler($eventKey)
    {
        switch ($eventKey) {
            case 'menu_click_test':
                return SendMessage::instance()->sendTextMsg('点击了一级菜单的 menuClick 按钮');
                break;
            case 'sub_menu_click_test':
                return SendMessage::instance()->sendTextMsg('点击了二级菜单的 subMenuClick 按钮');
                break;
            default:
                return SendMessage::instance()->sendTextMsg('嘻嘻');
                break;
        }
    }


}